<template>
  <el-card shadow="hover">
    <el-button
      type="primary"
      :icon="Plus"
      @click="showTrademarkList({ id: 0, tmName: '', logoUrl: '' })"
      >添加品牌</el-button
    >
    <el-table
      :data="trademarkList"
      border
      class="trademark-table"
      v-loading="loading"
      row-key="id"
    >
      <el-table-column label="序号" width="60" type="index" align="center" />
      <el-table-column prop="tmName" label="品牌名称" />
      <el-table-column prop="address" label="品牌LOGO">
        <template v-slot="{ row }">
          <!-- 
            lazy 图片懒加载
           -->
          <el-image
            :src="row.logoUrl"
            fit="fill"
            loading="lazy"
            class="trademark-logo"
          >
            <!-- 具名插槽：当图片加载失败时显示的内容 -->
            <template #error>
              <div class="image-slot">
                <el-icon><icon-picture /></el-icon>
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template v-slot="{ row }">
          <el-button
            type="warning"
            :icon="Edit"
            @click="showTrademarkList(row)"
          />
          <el-button type="danger" :icon="Delete" @click="deleTrademark(row)" />
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 6, 9]"
      layout=" prev, pager, next, jumper, ->, sizes, total"
      :total="total"
      @size-change="getTrademarkList"
      @current-change="getTrademarkList"
    />
    <!-- 弹窗-添加品牌&&修改品牌 -->
    <el-dialog
      v-model="dialogVisible"
      :title="trademarkFormData.updateId ? '修改品牌' : '添加品牌'"
    >
      <el-form
        label-width="120px"
        ref="trademarkFormRef"
        :model="trademarkFormData"
        :rules="trademarkFormRules"
      >
        <el-form-item label="品牌名称" prop="tmName">
          <el-input
            placeholder="请输入品牌名称"
            class="trademark-input"
            v-model="trademarkFormData.tmName"
          />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <!-- 上传upload -->
          <!-- 
            action 上传图片的服务器地址
            :show-file-list="false"  是否能上传多张图片(false不能上传多张图片)
            :on-success   上传图片成功触发函数
            :before-upload   上传图片之前触发函数(限制图片的大小和类型)
           -->
          <el-upload
            class="avatar-uploader"
            :action="BASE_URL + '/admin/product/upload'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademarkFormData.logoUrl"
              :src="trademarkFormData.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">
                只能上传jpg/png文件，且不超过200kb
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addTrademarkForm"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "XTrademark",
};
</script>

<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import {
  Plus,
  Edit,
  Delete,
  Picture as IconPicture,
} from "@element-plus/icons-vue";
import {
  getTrademarkListApi,
  addTrademarkFormApi,
  delTrademarkListApi,
  UpdateTrademarkListApi,
} from "@/api/product/trademark";
import type {
  TrademarkList,
  TrademarkItem,
} from "@/api/product/model/trademarkModel";
import { dividerProps, ElMessage, ElMessageBox } from "element-plus";

import type { UploadProps } from "element-plus";

//修改商品
// const editTitle = ref("");
// const editTrademarkList = async (row: TrademarkItem) => {
//1.打开弹窗
// dialogVisible.value = true;
// trademarkFormData.tmName = row.tmName;
// trademarkFormData.logoUrl = row.logoUrl;
// trademarkFormData.updateId = row.id;
//2. 校验通过，发送添加请求
// const { tmName, logoUrl } = trademarkFormData;
// const res = await UpdateTrademarkListApi(tmName, logoUrl);
// };

/****************************删除商品****************************** */
// const deleTrademark = async (id: any) => {
//   const res = await delTrademarkListApi(id);
//   ElMessage.success("删除商品成功");
//   getTrademarkList();
// };

const deleTrademark = (row: TrademarkItem) => {
  ElMessageBox.confirm(`你确定要删除 "${row.tmName}" 这条信息吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await delTrademarkListApi(row.id);
      ElMessage.success("删除商品成功");
      getTrademarkList();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
};
/***************************添加品牌********************************/
//点击确定addTrademarkForm
const addTrademarkForm = async () => {
  //1. 校验是否通过
  await trademarkFormRef.value.validate();
  //2. 校验通过，发送添加请求
  const { tmName, logoUrl, updateId } = trademarkFormData;

  //这时需要判断是否要有id，如果有id说明点的是"修改品牌", 如果没有说明点击的是"添加品牌"
  if (updateId) {
    // 发送添加请求
    const res = await UpdateTrademarkListApi(updateId, tmName, logoUrl);
    //修改成功信息
    ElMessage.success("修改品牌成功");
  } else {
    //3. 发送请求成功后，提示成功信息，关闭弹窗，重新获取列表数据
    // 发送添加请求
    const res = addTrademarkFormApi(tmName, logoUrl);
    //提示添加成功信息
    ElMessage.success("添加品牌成功");
  }
  //关闭弹窗
  dialogVisible.value = false;
  //重新获取列表数据
  getTrademarkList();
};

// 获取表单el-form的实例化
const trademarkFormRef = ref();

// 表单数据
const trademarkFormData = reactive({
  //表单参数名称看接口文档
  //品牌名称
  tmName: "",
  // 品牌LOGO
  logoUrl: "",
  updateId: 0,
});

//表单校验规则
const trademarkFormRules = reactive({
  //表单校验规则名字必须和数据名称保持一致
  tmName: [
    {
      //必填项
      required: true,
      //校验失败，提示错误信息
      message: "请输入品牌名称",
      //触发表单校验的时机： 失去光标
      trigger: "blur",
    },
    {
      min: 2,
      max: 10,
      message: "品牌名称必须为2-10位",
      trigger: "blur",
    },
  ],
  logoUrl: [
    {
      //必填项
      required: true,
      //校验失败，提示错误信息
      message: "请上传图片LOGO",
    },
  ],
});

/**********************弹窗的显示&&隐藏***************************/
const dialogVisible = ref(false);

// const addTrademarkList = () => {
//   //标题
//   editTitle.value = "添加品牌";
//   // 点击显示弹窗
//   dialogVisible.value = true;
// };

// 显示&隐藏的函数封装
const showTrademarkList = (row: TrademarkItem) => {
  // 点击显示弹窗
  dialogVisible.value = true;
  trademarkFormData.tmName = row.tmName;
  trademarkFormData.logoUrl = row.logoUrl;
  trademarkFormData.updateId = row.id;
  trademarkFormRef.value.clearValidate();
};

/*********************上传品牌图片**********************************/
//请求前缀
const BASE_URL = import.meta.env.VITE_API_URL;

//上传成功的图片地址
// const imageUrl = ref("");

//图片上传之前触发的回调函数
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  /**
   rawFile 上传图片文件
   type 图片类型
   size 图片大小
   */
  const validImageTypes = ["image/jpg", "image/png"];

  if (!validImageTypes.includes(rawFile.type)) {
    ElMessage.error("图片只能上传jpg和png格式的");
    // 如果返回false，就会终止
    return false;
  } else if (rawFile.size > 5 * 1024 * 1024) {
    ElMessage.error("图片的大小只能上传200kb的");
    return false;
  }
  // 如果返回true,就会继续上传
  return true;
};

//图片上传成功触发的回调函数
const handleAvatarSuccess: UploadProps["onSuccess"] = (response) => {
  trademarkFormData.logoUrl = response.data;
  // console.log(response);
  //上传成功后，清空表单的验证信息
  // trademarkFormRef.value.clearValidate()//清空所有的表单验证信息
  trademarkFormRef.value.clearValidate(["logoUrl"]); //清空logoUrl表单项的验证信息
};

/**********************分页品牌列表的数据***************************/
//品牌列表
const trademarkList = ref<TrademarkList>([]);

//loading加载
const loading = ref(false);
//当前页码
const currentPage = ref(1);
// 每页条数
const pageSize = ref(3);
// 总数
const total = ref(0);

//封装公共发送请求函数
const getTrademarkList = async () => {
  loading.value = true;
  const res = await getTrademarkListApi(currentPage.value, pageSize.value);
  console.log(res);
  total.value = res.total;
  trademarkList.value = res.records;
  loading.value = false;
};

onMounted(getTrademarkList);

// const handleSizeChange = (val: number) => {
//   getTrademarkList();
// };
// const handleCurrentChange = (val: number) => {
//   getTrademarkList();
// };
</script>

<style scoped>
.trademark-logo {
  width: 180px;
  height: 100px;
}

.trademark-input {
  width: 500px;
}

.trademark-table {
  margin-top: 20px;
  margin-bottom: 30px;
}
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 30px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
